package com.dp.shop.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.common.domain.dto.Result;
import com.dp.shop.Client.CacheClient;
import com.dp.common.utils.RedisData;
import com.dp.shop.domain.po.Shop;
import com.dp.shop.mapper.ShopMapper;
import com.dp.shop.service.IShopService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.dp.common.constants.RedisConstants.*;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Resource
    private CacheClient cacheClient;
    // TODO 缓存三兄弟
    @Override
    public Result queryById(Long id) {
//        Shop shop = queryWithPassThrough(id);
//        Shop shop = queryWithMutex(id);
//        Shop shop = queryWithLogicalExpire(id);
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    /**
     * 缓存击穿-逻辑过期
     *
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        // 首先根据id查询Redis缓存
        String shopJson = stringRedisTemplate.opsForValue()
                .get(CACHE_SHOP_KEY + id);
        if (StrUtil.isBlank(shopJson)) {
            // 未命中
            return null;
        } else {
            // 命中-判断缓存是否过期
            RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);// 反序列化
            JSONObject data = (JSONObject) redisData.getData();
            Shop shop = JSONUtil.toBean(data, Shop.class);
            LocalDateTime expireTime = redisData.getExpireTime();
            if ( expireTime.isAfter(LocalDateTime.now()) ) {
                // 未过期-返回商铺信息
                return shop;
            }
            // 已过期-缓存重建
            // 获取互斥锁
            String lockKey = LOCK_SHOP_KEY + id;
            if (tryLock(lockKey)) {
                // 获取锁成功-开启独立线程
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        this.saveShop2Redis(id, 20L);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        unlock(lockKey);
                    }
                });
            }
            // 失败-返回过期信息
            return shop;
        }
    }
    /**
     * 缓存击穿-互斥锁
     *
     * @param id
     * @return
     */

    public Shop queryWithMutex(Long id) {
        Shop shop = null;
        // 首先根据id查询Redis缓存
        String shopJson = stringRedisTemplate.opsForValue()
                .get(CACHE_SHOP_KEY + id);
        // 命中则返回
        if (StrUtil.isNotBlank(shopJson)) {
            shop = JSONUtil.toBean(shopJson, Shop.class);// 反序列化
            return shop;
        } else {
            // 命中是否是空值
            if (shopJson != null) {
                return null;
            }
            try {
                // 尝试获取互斥锁判断是否获取成功
                if (!tryLock(LOCK_SHOP_KEY + id)) {
                    // 失败则休眠并重试
                    Thread.sleep(50);
                    return queryWithMutex(id);
                }
                // 未命中则查询数据库
                shop = getById(id);
                if (shop == null) {
                    // 将空值写入Redis
                    stringRedisTemplate.opsForValue()
                            .set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null;
                }
                // 添加到Redis缓存
                stringRedisTemplate.opsForValue()
                        .set(CACHE_SHOP_KEY + id,
                                JSONUtil.toJsonStr(shop),
                                CACHE_SHOP_TTL, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                // 释放互斥锁
                unlock(LOCK_SHOP_KEY + id);
            }
            return shop;
        }
    }

    /**
     * 缓存穿透-缓存空值
     *
     * @param id
     * @return
     */

    public Shop queryWithPassThrough(Long id) {
        // 首先根据id查询Redis缓存
        String shopJson = stringRedisTemplate.opsForValue()
                .get(CACHE_SHOP_KEY + id);
        // 命中则返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);// 反序列化
            return shop;
        } else {
            // 命中是否是空值
            if (shopJson != null) {
                return null;
            }
            // 未命中则查询数据库
            Shop shop = getById(id);
            if (shop == null) {
                // 将空值写入Redis
                stringRedisTemplate.opsForValue()
                        .set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 添加到Redis缓存
            stringRedisTemplate.opsForValue()
                    .set(CACHE_SHOP_KEY + id,
                            JSONUtil.toJsonStr(shop),
                            CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        // 先更新数据库
        updateById(shop);
        // 再删除Redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 模拟缓存预热
     */
    public void saveShop2Redis(Long id, Long expireSeconds) {
        // 查询店铺数据
        Shop shop = getById(id);
        // 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(redisData));
    }
}
